package com.yunlan.nacos.consumer.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yunlan.nacos.service2.api.Service2Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RestConsumerController {

    @Value("${provider.address}")
    private String providerUrl;

    private final static String providerId = "nacos-restful-provider";

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Reference
    Service2Api service2Api;


    @GetMapping("/call")
    public String call() {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(providerUrl+"/service", String.class);
        return "消费者调用生产者返回的信息:"+result;
    }

    @GetMapping("/service")
    public String service() {
        RestTemplate restTemplate = new RestTemplate();

        ServiceInstance serviceInstance = loadBalancerClient.choose(providerId);
        String result = restTemplate.getForObject(serviceInstance.getUri()+"/service", String.class);
        System.out.println(serviceInstance.getUri());
        System.out.println(serviceInstance.getHost());
        return "消费者调用生产者返回的信息:"+result+"  "+serviceInstance.getPort();
    }

    @GetMapping("/dubbo")
    public String dubbo() {
        String result = service2Api.sayHello("张洁");
        return "消费者调用生产者返回的信息:"+result;
    }
}
